/*
 * Copyright 2017 Baiyyy
 * @(#)KettleJobTask.java
 */
package com.byyy.ccts.modules.task.task;

import com.byyy.ccts.core.base.ILogBase;
import com.byyy.ccts.modules.sys.Constants;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * Created by DELL on 2018-6-27.
 */
@Component
public class KettleJobTask implements ILogBase {

    static {
        try {
            KettleEnvironment.init();
        } catch (KettleException e) {
            logger.error("Kettle初始化失败", e);
        }
    }
    /**
     * 执行KETTLE JOB
     * @param param
     */
    public static void runJob(String param){
        logger.debug("Kettle任务执行开始：{}", param);
        try {
            String jobFile = Constants.CLASS_PATH + "etl" + File.separator + param;
            //jobname 是Job脚本的路径及名称
            JobMeta jobMeta = new JobMeta(jobFile, null);
            Job job = new Job(null, jobMeta);
            //向Job 脚本传递参数，脚本中获取参数值：${参数名}
            job.start();
            job.waitUntilFinished();
            if (job.getErrors() > 0) {
                logger.error("Kettle任务执行失败");
            }
        } catch (KettleException e) {
            logger.error("Kettle任务执行失败", e);
        }
        logger.debug("Kettle任务执行结束");
    }

    /**
     * 执行KETTLE TRANS
     * @param param
     */
    public static void runTrans(String param) {
        logger.debug("Kettle任务执行开始：{}", param);
        try {
            String jobFile = Constants.CLASS_PATH + "etl" + File.pathSeparator + param;
            TransMeta transMeta = new TransMeta(jobFile);
            Trans trans = new Trans(transMeta);
            trans.prepareExecution(null);
            trans.startThreads();
            trans.waitUntilFinished();
            if (trans.getErrors()!=0) {
                logger.error("Kettle任务执行失败");
            }
        } catch (KettleException e) {
            logger.error("Kettle任务执行失败", e);
        }
        logger.debug("Kettle任务执行结束");
    }

}
